package chatroom;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 *客户端输出流的线程
 * @Author: xxf
 * @CreateDate: 2020/9/4 19:11
 * 1.构造方法传参获取socket对象
 * 2.读取客户端第一次注册用户名
 * 3.循环向服务器发消息
 */
public class WriteThread extends Thread{
    /**
     * 字符输出流
     */
    BufferedWriter writer;

    /**
    *通过构造方法将用户的socket对象传过来,调用socket.getOutputStream(),向服务器发消息
     *
    *@param socket1
    */
    public WriteThread(Socket socket1) {
        try {
            writer =new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream()));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        Scanner sc=new Scanner(System.in);

        try {
            //第一次输入需要客户端注册用户名发送给服务器
            System.out.println("请输入用户名:");
            String cname=sc.nextLine();
            writer.write(cname);
            writer.newLine();
            writer.flush();

            while (true) {
                String sendMess = sc.nextLine();
                writer.write(sendMess);
                writer.newLine();
                writer.flush();
            }
        } catch (IOException e) {
                e.printStackTrace();
        }
    }
}

